package com.timmy.ble;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.search.SearchResult;
import com.timmy.ble.callback.BleCallbackImpl;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.inuker.bluetooth.library.Code.REQUEST_FAILED;
import static com.inuker.bluetooth.library.Code.REQUEST_SUCCESS;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    private static final String TAG = MainActivity.class.getSimpleName();
    @BindView(R.id.listview)
    ListView mListview;
    private ProgressDialog mProgressDialog;
    private DeviceAdapter mDeviceAdapter;
    private BleManager mBleManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        // CrashReport.initCrashReport(this);


        //mBleManager.disconnect();


        mBleManager = BleManager.getInstance(this);

        String sdcard = Environment.getExternalStorageDirectory().toString() + "/zzzzzzzzzzzzzz.zip";

        Log.i(TAG, "onCreate: " + sdcard);
        Log.i(TAG, "onCreate: " + (new File(sdcard).exists()));


//        mBleManager.registerBluetoothStateListener(l);


        mDeviceAdapter = new DeviceAdapter(this);
        mListview.setAdapter(mDeviceAdapter);

        mListview.setOnItemClickListener(this);
    }

    // 和校验
    public byte sumCheck(byte[] data) {
        int sum = 0;
        //for (int i = 1; i < data.length - 1; i++) {
        for (int i = 0; i < data.length; i++) {
            int d = data[i] & 0x0FF;
            sum += d;
        }

        return (byte) (0xff & sum);
    }

    BleCallbackImpl l = new BleCallbackImpl() {
        @Override
        public void onBluetoothStateChanged(boolean openOrClosed) {
            hideProgressDialog();
        }
    };


    private void showProgressDialog(String title, String message) {

        if (mProgressDialog == null) {
            mProgressDialog = ProgressDialog.show(MainActivity.this, title, message, false);
        } else if (mProgressDialog.isShowing()) {
            mProgressDialog.setTitle(title);
            mProgressDialog.setMessage(message);
        }
        mProgressDialog.show();
    }

    private void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    @OnClick({R.id.btn_scan, R.id.stop_scan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_scan:
                showProgressDialog("", "正在扫描...");
                mBleManager.search(new BleCallbackImpl() {
                    @Override
                    public void onScan(SearchResult result) {
                        // 扫描到了设备
                        mDeviceAdapter.addData(result);
                    }

                    @Override
                    public void onScanStop() {
                        // 停止扫描设备
                        hideProgressDialog();
                    }
                });
                break;
            case R.id.stop_scan:
                hideProgressDialog();
                mBleManager.stopSearch();
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        showProgressDialog("", "正在连接...");

        // ListView 条目点击事件
        SearchResult result = (SearchResult) mDeviceAdapter.getItem(position);

        mBleManager.connect(result.getAddress(), new BleCallbackImpl() {
            @Override
            public void onResponse(int code, BleGattProfile data) {


                hideProgressDialog();

                if (code == REQUEST_SUCCESS) {
                    // 连接成功
                    // 跳转页面
                    Intent intent = new Intent(MainActivity.this, InfoActivity.class);
                    startActivity(intent);
                    finish();
                } else if (code == REQUEST_FAILED) {
                    // 连接失败
                    Toast.makeText(MainActivity.this, "连接蓝牙失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // mBleManager.unregisterBluetoothStateListener(l);
    }

}
